package com.boc.image.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.boc.bus.control.BusOutputResult;
import com.boc.ibatis.config.IbatisSqlClient;
import com.boc.news.beans.GlobalP;

public class Albums {
	
	/**
	 * 保存相册
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult saveUserAlbums(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			//查看相册名称是否存在
			String userid = request.getSession().getAttribute("userId").toString();
			m.put("nUserid", userid);
			
			Integer count = (Integer)IbatisSqlClient.sqlMapClient.queryForObject("image_t_img_xc.getAlbumsNameCount",m);
			
			if(count.intValue() > 0) {
				result.addValue("PN_RET", "-1");
				result.addValue("PC_MSG", "该相册名称已存在!");
				return result;
			}
			m.put("cZt", "1");
			IbatisSqlClient.sqlMapClient.insert("image_t_img_xc.ibatorgenerated_insert", m);
			result.addValue("PN_RET", "0");
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 取用户相册
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public List getUserAlbums(String userid) {
		List list = null;
		try {
			Map m = new HashMap();
			m.put("nUserid", userid);
			m.put("cZt", "1");
			list = IbatisSqlClient.sqlMapClient.queryForList("image_t_img_xc.getAlbumsImgNums", m);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	/**
	 * 修改相册名称
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult updUserAlbums(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			String userid = request.getSession().getAttribute("userId").toString();
			IbatisSqlClient.sqlMapClient.update("image_t_img_xc.ibatorgenerated_updateByPrimaryKeySelective", m);
			result.addValue("PN_RET", "0");
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 删除相册
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult deleteUserAlbums(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			String userid = request.getSession().getAttribute("userId").toString();
			Integer count = (Integer)IbatisSqlClient.sqlMapClient.queryForObject("image_t_img_xc.getImgCount", m);
			if(count.intValue() > 0) {
				result.addValue("PN_RET", "-1");
				result.addValue("PC_MSG", "该相册已上传图片,不能删除相册!");
				return result;
			}
			IbatisSqlClient.sqlMapClient.delete("image_t_img_xc.ibatorgenerated_deleteByPrimaryKey", m);
			result.addValue("PN_RET", "0");
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 取用户上传的图片
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult getUserImage(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			String userid = request.getSession().getAttribute("userId").toString();
			Integer count = (Integer)IbatisSqlClient.sqlMapClient.queryForObject("image_t_img_xc.getImgCount", m);
			if(count.intValue() > 0) {
				result.addValue("PN_RET", "-1");
				result.addValue("PC_MSG", "该相册已上传图片,不能删除相册!");
				return result;
			}
			IbatisSqlClient.sqlMapClient.delete("image_t_img_xc.ibatorgenerated_deleteByPrimaryKey", m);
			result.addValue("PN_RET", "0");
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 取分页数据
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult getPageContent(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			int currPage = 0;//当前页
			int pageRows = 0;//每页显示行数
			int totalPages = 0;//总页数
			int totalRows = 0;//总行数
			currPage = Integer.parseInt(m.get("currPage").toString());
			pageRows = Integer.parseInt(m.get("pageRows").toString());
			if(currPage == -1) {
				Object rows = IbatisSqlClient.sqlMapClient.queryForObject("image_t_img_image.client_getRows",m);
				totalRows = Integer.parseInt(rows.toString());
				totalPages = totalRows % pageRows == 0? (totalRows / pageRows):(totalRows / pageRows)+1;
				result.addValue("totalRows", new Integer(totalRows));
				result.addValue("totalPages", new Integer(totalPages));
			}
			List list = IbatisSqlClient.sqlMapClient.queryForList(
					"image_t_img_image.getContent", m,
					(currPage - 1) * pageRows, pageRows);
			result.addValue("P_RESULT", list);
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 修改图片信息
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult updUserImage(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			IbatisSqlClient.sqlMapClient.update("image_t_img_image.ibatorgenerated_updateByPrimaryKeySelective", m);
			result.addValue("PN_RET", "0");
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 删除用户图片
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult deleteUserImage(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		String str = null;
		try {
			m.put("nUserid", request.getSession().getAttribute("userId"));
			str = (String)IbatisSqlClient.sqlMapClient.queryForObject("image_t_img_image.getOldPath",m);
			IbatisSqlClient.sqlMapClient.insert("image_procedure.delUserImage",m);
			if(str != null) {
				String oldPath = GlobalP.BASE_FOLDER_PATH+File.separator+str;
				File f = new File(oldPath);
				if(f.exists()) {
					f.delete();
				}
			}
			result.addValue("PN_RET", m.get("PN_RET"));
			result.addValue("PC_MSG", m.get("PC_MSG"));
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 取图片路径
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult getImagPath(HttpServletRequest request,
			HttpServletResponse response, Map m) {
		BusOutputResult result = new BusOutputResult();
		try {
			Object str = IbatisSqlClient.sqlMapClient.queryForObject("image_t_img_image.getImgPath",m);
			result.addValue("path", GlobalP.IMAGE_DOMAIN_PATH + "/" + str);
			result.addValue("PN_RET", "0");
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 上传封面照片
	 * @param request
	 * @param response
	 * @param m
	 * @return
	 */
	public BusOutputResult uploadAlbumsImg(HttpServletRequest request,
			HttpServletResponse response, Map m)  throws UnsupportedEncodingException , IOException{
		BusOutputResult result = new BusOutputResult();
		request.setCharacterEncoding("UTF-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);// 10M
		// 设置临时文件存储位置
		String base = request.getRealPath("/")+"images"+File.separator+"albums";
		File file = new File(base);
		if (!file.exists())
			file.mkdirs();
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(10002400000l);// 100M
		// 设置整个request的最大值
		upload.setSizeMax(10002400000l);// 1000M
		upload.setHeaderEncoding("UTF-8");
		String path = base+File.separator+m.get("nId")+".bin";
		try {
			m.put("cPath", m.get("nId")+".bin");
			IbatisSqlClient.sqlMapClient.update("image_t_img_xc.ibatorgenerated_updateByPrimaryKeySelective",m);
			List<?> items = upload.parseRequest(request);
			FileItem item = null;
			for (int i = 0; i < items.size(); i++) {
				item = (FileItem) items.get(i);
				// 保存文件
				if (!item.isFormField() && item.getName().length() > 0) {
					item.write(new File(path));
				}
			}
			result.addValue("PN_RET", "0");
			
		} catch (Exception e) {
			result.addValue("PN_RET", "-1");
			result.addValue("PC_MSG", e.getMessage());
			throw new IOException();
		}
		return result;
	}
	
}
